import 'package:flutter/material.dart';
import '../theme/app_theme.dart';






import 'package:intl/intl.dart';

class PregnancyPreparationScreen extends StatefulWidget {
  const PregnancyPreparationScreen({super.key});

  @override
  State<PregnancyPreparationScreen> createState() => _PregnancyPreparationScreenState();
}

class _PregnancyPreparationScreenState extends State<PregnancyPreparationScreen> {
  
  List<dynamic> _temperatureRecords = [];
  
  List<dynamic> _ovulationTests = [];
  
  final List<dynamic> _preparationRecords = [];
  final DateTime _currentDate = DateTime.now();
  bool _isLoading = false;
  double _predictedPregnancyRate = 0.0;
  String _fertilityAdvice = '';
  
  


  @override
  void initState() {
    super.initState();
    _loadData();
  }

  void _loadData() async {
    setState(() => _isLoading = true);
    
    try {
      // 直接加载示例数据，因为 userProfile 未被使用
      _loadSampleData();
      
      _predictedPregnancyRate = 20.0;
      _fertilityAdvice = '今日受孕概率中等，可以考虑安排同房。';
      
    } catch (e) {
      debugPrint('加载备孕数据失败: $e');
      
      _loadSampleData();
    } finally {
      setState(() => _isLoading = false);
    }
  }

  void _convertPreparationRecordsToModels() {
    _temperatureRecords.clear();
    _ovulationTests.clear();
    
    
    for (var record in _preparationRecords) {
      
      if (record.basalTemperature != null) {
        _temperatureRecords.add({
          'date': record.date,
          'temperature': record.basalTemperature!,
        });
      }
      
      
      if (record.ovulationTestResult != null) {
        try {
          
          final parts = record.ovulationTestResult!.split('|');
          final strength = int.tryParse(parts[0]) ?? 0;
          final interpretation = parts.length > 1 ? parts[1] : '未知结果';
          final imagePath = parts.length > 2 ? parts[2] : '';
          
          _ovulationTests.add({
            'date': record.date,
            'imagePath': imagePath,
            'resultStrength': strength,
            'interpretation': interpretation,
          });
        } catch (e) {
          debugPrint('解析排卵试纸结果失败: $e');
        }
      }
    }
    
    
    _temperatureRecords.sort((a, b) => a['date'].compareTo(b['date']));
    _ovulationTests.sort((a, b) => b['date'].compareTo(a['date']));
  }
  
  void _loadSampleData() {
    
    _temperatureRecords = [
      {'date': DateTime.now().subtract(const Duration(days: 10)), 'temperature': 36.2},
      {'date': DateTime.now().subtract(const Duration(days: 9)), 'temperature': 36.3},
      {'date': DateTime.now().subtract(const Duration(days: 8)), 'temperature': 36.2},
      {'date': DateTime.now().subtract(const Duration(days: 7)), 'temperature': 36.4},
      {'date': DateTime.now().subtract(const Duration(days: 6)), 'temperature': 36.5},
      {'date': DateTime.now().subtract(const Duration(days: 5)), 'temperature': 36.7},
      {'date': DateTime.now().subtract(const Duration(days: 4)), 'temperature': 36.9},
      {'date': DateTime.now().subtract(const Duration(days: 3)), 'temperature': 36.8},
      {'date': DateTime.now().subtract(const Duration(days: 2)), 'temperature': 36.9},
      {'date': DateTime.now().subtract(const Duration(days: 1)), 'temperature': 37.0},
    ];
    
    _ovulationTests = [
      {
        'date': DateTime.now().subtract(const Duration(days: 3)),
        'imagePath': '',
        'resultStrength': 2,
        'interpretation': '弱阳，接近排卵期',
      },
      {
        'date': DateTime.now().subtract(const Duration(days: 2)),
        'imagePath': '',
        'resultStrength': 3,
        'interpretation': '强阳，即将排卵',
      },
    ];
    
    const predictedRate = 35.0;
    const advice = '今日受孕概率较高，建议安排同房。';
    _predictedPregnancyRate = predictedRate;
    _fertilityAdvice = advice;
  }
  
  void _showTemperatureInputDialog() {
    double temperature = 36.5;
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('记录基础体温'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(DateFormat('yyyy年MM月dd日').format(_currentDate), style: AppTheme.subtitleStyle),
            const SizedBox(height: 16),
            Slider(
              min: 35.0,
              max: 38.0,
              divisions: 30,
              value: temperature,
              onChanged: (value) => temperature = value,
              label: temperature.toStringAsFixed(1),
              activeColor: AppTheme.primaryColor,
            ),
            Text('体温: ${temperature.toStringAsFixed(1)}°C', style: AppTheme.bodyStyle),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              try {
                
                final formattedDate = DateFormat('yyyy-MM-dd').format(_currentDate);
                var existingRecordIndex = _preparationRecords.indexWhere(
                  (r) => DateFormat('yyyy-MM-dd').format(r['date']) == formattedDate
                );
                
                if (existingRecordIndex >= 0) {
                  
                  _preparationRecords[existingRecordIndex]['basalTemperature'] = temperature;
                } else {
                  
                  _preparationRecords.add({
                    'date': _currentDate,
                    'basalTemperature': temperature,
                    'ovulationTestResult': null,
                    'notes': ''
                  });
                }
                
                
                setState(() {
                  
                  _convertPreparationRecordsToModels();
                });
                
                Navigator.pop(context);
                _showSuccessMessage('体温记录成功');
              } catch (e) {
                debugPrint('保存体温记录失败: $e');
                Navigator.pop(context);
                _showSuccessMessage('保存失败，请重试');
              }
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  void _showOvulationTestCaptureDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('排卵试纸测试'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(DateFormat('yyyy年MM月dd日').format(_currentDate), style: AppTheme.subtitleStyle),
            const SizedBox(height: 16),
            Container(
              height: 200,
              color: AppTheme.background,
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: const [
                    Icon(Icons.camera_alt, size: 64, color: AppTheme.primaryColor),
                    SizedBox(height: 8),
                    Text('拍照识别排卵试纸'),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),
            Text('提示：请在光线充足的环境下拍摄，确保试纸平整清晰', style: AppTheme.bodyStyle.copyWith(fontSize: 12)),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              try {
                
                const int resultStrength = 3;
                const String interpretation = '强阳，24-36小时内即将排卵';
                const String imagePath = ''; 

                
                
                const String testResult = '$resultStrength|$interpretation|$imagePath';
                
                
                final formattedDate = DateFormat('yyyy-MM-dd').format(_currentDate);
                var existingRecordIndex = _preparationRecords.indexWhere(
                  (r) => DateFormat('yyyy-MM-dd').format(r['date']) == formattedDate
                );
                
                if (existingRecordIndex >= 0) {
                  
                  _preparationRecords[existingRecordIndex]['ovulationTestResult'] = testResult;
                } else {
                  
                  _preparationRecords.add({
                    'date': _currentDate,
                    'basalTemperature': null,
                    'ovulationTestResult': testResult,
                    'notes': ''
                  });
                }
                
                
                setState(() {
                  
                  _convertPreparationRecordsToModels();
                });
                
                Navigator.pop(context);
                _showSuccessMessage('排卵试纸识别成功');
              } catch (e) {
                debugPrint('保存排卵试纸记录失败: $e');
                Navigator.pop(context);
                _showSuccessMessage('保存失败，请重试');
              }
            },
            child: const Text('拍照识别'),
          ),
        ],
      ),
    );
  }

  void _showSuccessMessage(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message)),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppTheme.background,
      appBar: AppBar(
        backgroundColor: AppTheme.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.pop(context),
          color: AppTheme.textPrimary,
        ),
        title: Text('备孕模式', style: AppTheme.titleStyle),
      ),
      body: _isLoading ? _buildLoadingView() : _buildMainView(),
    );
  }

  Widget _buildLoadingView() {
    return const Center(child: CircularProgressIndicator());
  }

  Widget _buildMainView() {
    return SingleChildScrollView(
      child: Column(
        children: [
          
          Container(
            margin: const EdgeInsets.all(16),
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: AppTheme.white,
              borderRadius: BorderRadius.circular(12),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withValues(alpha: 0.05),
                  blurRadius: 10,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text('今日备孕建议', style: AppTheme.subtitleStyle),
                    Text(DateFormat('MM月dd日').format(_currentDate), style: AppTheme.bodyStyle.copyWith(color: AppTheme.textSecondary)),
                  ],
                ),
                const SizedBox(height: 12),
                Row(
                  children: [
                    Container(
                      padding: const EdgeInsets.all(8),
                      decoration: BoxDecoration(
                        color: AppTheme.primaryColor.withValues(alpha: 0.1),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Text(
                        '受孕概率 ${_predictedPregnancyRate.toStringAsFixed(0)}%',
                        style: TextStyle(color: AppTheme.primaryColor, fontWeight: FontWeight.bold),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 12),
                Text(_fertilityAdvice, style: AppTheme.bodyStyle),
              ],
            ),
          ),

          
          Container(
            margin: const EdgeInsets.symmetric(horizontal: 16),
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: AppTheme.white,
              borderRadius: BorderRadius.circular(12),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withValues(alpha: 0.05),
                  blurRadius: 10,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children:
               [
                Text('日常记录', style: AppTheme.subtitleStyle),
                const SizedBox(height: 16),
                GridView.count(
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  crossAxisCount: 2,
                  crossAxisSpacing: 12,
                  mainAxisSpacing: 12,
                  children: [
                    _buildFunctionCard(
                      icon: Icons.thermostat, 
                      title: '基础体温', 
                      subtitle: '记录基础体温变化',
                      onTap: _showTemperatureInputDialog,
                    ),
                    _buildFunctionCard(
                      icon: Icons.medical_services, 
                      title: '排卵试纸', 
                      subtitle: '拍照识别排卵试纸',
                      onTap: _showOvulationTestCaptureDialog,
                    ),
                  ],
                ),
              ],
            ),
          ),

          
          if (_temperatureRecords.isNotEmpty)
            Container(
              margin: const EdgeInsets.all(16),
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: AppTheme.white,
                borderRadius: BorderRadius.circular(12),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withValues(alpha: 0.05),
                    blurRadius: 10,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children:
                 [
                  Text('体温变化趋势', style: AppTheme.subtitleStyle),
                  const SizedBox(height: 16),
                  Container(
                    height: 200,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text('基础体温记录', style: AppTheme.subtitleStyle),
                        const SizedBox(height: 8),
                        _temperatureRecords.isEmpty
                            ? Text('暂无体温记录', style: AppTheme.bodyStyle)
                            : Text('共 ${_temperatureRecords.length} 条体温记录', style: AppTheme.bodyStyle),
                      ],
                    ),
                  )
                ],
              ),
            ),

          
          if (_ovulationTests.isNotEmpty)
            Container(
              margin: const EdgeInsets.symmetric(horizontal: 16),
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: AppTheme.white,
                borderRadius: BorderRadius.circular(12),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withValues(alpha: 0.05),
                    blurRadius: 10,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children:
                 [
                  Text('排卵试纸记录', style: AppTheme.subtitleStyle),
                  const SizedBox(height: 16),
                  ListView.builder(
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                    itemCount: _ovulationTests.length,
                    itemBuilder: (context, index) {
                      return Card(
                        margin: EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                        elevation: 1,
                        child: ListTile(
                          title: Text('排卵测试记录'),
                          subtitle: Text('日期: ${_ovulationTests[index]['date']}'),
                          trailing: Icon(Icons.arrow_forward),
                        ),
                      );
                    },
                  ),
                ],
              ),
            ),

          const SizedBox(height: 24),
        ],
      ),
    );
  }

  Widget _buildFunctionCard({required IconData icon, required String title, required String subtitle, required VoidCallback onTap}) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: AppTheme.background,
          borderRadius: BorderRadius.circular(12),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children:
           [
            Container(
              padding: const EdgeInsets.all(8),
              decoration: BoxDecoration(
                color: AppTheme.primaryColor.withValues(alpha: 0.1),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Icon(icon, size: 24, color: AppTheme.primaryColor),
            ),
            const SizedBox(height: 8),
            Text(title, style: AppTheme.bodyStyle.copyWith(fontWeight: FontWeight.bold)),
            Text(subtitle, style: AppTheme.bodyStyle.copyWith(fontSize: 12, color: AppTheme.textSecondary)),
          ],
        ),
      ),
    );
  }
}
